/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cn.ekuma.epos.datalogic.update;

import cn.ekuma.epos.datalogic.I_DataLogicSystem;
import cn.ekuma.epos.module.DefaultDataLogicModel;
import cn.ekuma.rabbit.ModelManager;

import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.JMessageDialog;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.data.loader.BatchSentence;
import com.openbravo.data.loader.BatchSentenceResource;
import com.openbravo.data.loader.I_Session;
import com.openbravo.pos.base.AppConfig;
import com.openbravo.pos.base.AppLocal;
import com.openbravo.pos.base.AppProperties;
import com.openbravo.pos.base.AppViewConnection;
import com.openbravo.pos.instance.InstanceQuery;

import java.io.File;
import java.util.Locale;
import java.util.regex.Matcher;

import javax.swing.JOptionPane;

import net.xeoh.plugins.base.PluginManager;
import net.xeoh.plugins.base.impl.PluginManagerFactory;

/**
 *
 * @author Administrator
 */
public class Update230 {
   private I_Session session;
   private I_DataLogicSystem m_dlSystem;


   public Update230(){   
   }

// Create or upgrade the database if database version is not the expected

    public boolean update(AppProperties m_props){

        // Database start
        try {
            session = new AppViewConnection().createSession(m_props);
        } catch (BasicException e) {
            JMessageDialog.showMessage(new java.awt.Frame(), new MessageInf(MessageInf.SGN_DANGER, e.getMessage(), e));
            return false;
        }
        PluginManager pmf = PluginManagerFactory.createPluginManager();
        pmf.addPluginsFrom(new File("plugins/").toURI());
        
        ModelManager manager=new ModelManager(pmf, m_props);
        manager.setSession(session);
        DefaultDataLogicModel dataLogic=(DefaultDataLogicModel) manager.getModelByName(DefaultDataLogicModel.NAME);
        m_dlSystem =dataLogic.getDLSystem();

        String sDBVersion = readDataBaseVersion();
        if(sDBVersion==null||!AppLocal.APP_VERSION.equalsIgnoreCase(sDBVersion)) {
            JMessageDialog.showMessage(new java.awt.Frame(), new MessageInf(MessageInf.SGN_DANGER, AppLocal.getIntString("message.appversionnosuppot")));
             session.close();
             return false;
        }

         // Create or upgrade database
        String sScript = sDBVersion == null
                    ? m_dlSystem.getInitScript() + "-create.sql"
                    : m_dlSystem.getInitScript() + "-epos-upgrade-2.30.sql";
            if (Update230.class.getResource(sScript) == null) {
                JMessageDialog.showMessage(new java.awt.Frame(), new MessageInf(MessageInf.SGN_DANGER, sDBVersion == null
                            ? AppLocal.getIntString("message.databasenotsupported", session.getDB().getName()) // Create script does not exists. Database not supported
                            : AppLocal.getIntString("message.noupdatescript"))); // Upgrade script does not exist.
                session.close();
                return false;
            } else {
               
                // Create or upgrade script exists.
                if (JOptionPane.showConfirmDialog(new java.awt.Frame()
                        , AppLocal.getIntString(sDBVersion == null ? "message.createdatabase" : "message.updatedatabase")+"<--"+sScript
                        , AppLocal.getIntString("message.title")
                        , JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {

                    try {
                        BatchSentence bsentence = new BatchSentenceResource(session, sScript);
                        bsentence.putParameter("APP_ID", Matcher.quoteReplacement(AppLocal.APP_ID));
                        bsentence.putParameter("APP_NAME", Matcher.quoteReplacement(AppLocal.APP_NAME));
                        bsentence.putParameter("APP_VERSION", Matcher.quoteReplacement(AppLocal.APP_VERSION));
                        //bsentence.putParameter("AD_CLIENT_ID", Matcher.quoteReplacement(AppConfig.getAppProperty(Adempiere.AD_CLIENT_ID)));
                        //bsentence.putParameter("AD_ORG_ID", Matcher.quoteReplacement(AppConfig.getAppProperty(Adempiere.AD_ORG_ID)));

                        java.util.List l = bsentence.list();
                        if (l.size() > 0) {
                            JMessageDialog.showMessage(new java.awt.Frame(), new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("Database.ScriptWarning"), l.toArray(new Throwable[l.size()])));
                        }
                   } catch (BasicException e) {
                        JMessageDialog.showMessage(new java.awt.Frame(), new MessageInf(MessageInf.SGN_DANGER, AppLocal.getIntString("Database.ScriptError"), e));
                        session.close();
                        return false;
                    }
                } else {
                    session.close();
                    return false;
                }
            }
        return true;
    }

   private String readDataBaseVersion() {
        try {
            return m_dlSystem.findVersion();
        } catch (BasicException ed) {
            return null;
        }
    }

       public static void main(final String args[]) {
        

        if (!registerApp()) {
            System.exit(1);
        }

        AppConfig config = new AppConfig(args);
        config.load();

        // set Locale.
        String slang = config.getProperty("user.language");
        String scountry = config.getProperty("user.country");
        String svariant = config.getProperty("user.variant");
        if (slang != null && !slang.equals("") && scountry != null && svariant != null) {
            Locale.setDefault(new Locale(slang, scountry, svariant));
        }
        new Update230().update(config);
        System.exit(1);
    }

   public static boolean registerApp() {

        // vemos si existe alguna instancia
        InstanceQuery i = null;
        try {
            i = new InstanceQuery();
            i.getAppMessage().restoreWindow();
            return false;
        } catch (Exception e) {
            return true;
        }
    }
}
